﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Net;
using System.IO;
using System.Diagnostics;

namespace Proxy3
{
    public class ProxyInfoArgs : EventArgs
    {
        public int Speed;
        public string Proxy;
        public ProxyInfoArgs(string proxy, int speed)
        {
            Proxy = proxy;
            Speed = speed;
        }
    }

    class SubThread
    {
        public string proxyString;
        public delegate void MessageEventHandler(object sender, ProxyInfoArgs e);
        public event MessageEventHandler MessageSend;

        public SubThread() { }
        public SubThread(string proxy)
        {
            proxyString = proxy;
        }
        public void OnMessageSend(object sender, ProxyInfoArgs e)
        {
            if (MessageSend != null)
                this.MessageSend(sender, e);
        }
        public System.Threading.Thread testThread;
        public void TestProxy()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            try
            {


                var request = (HttpWebRequest)HttpWebRequest.Create("http://chong.b3log.org/");

                // 代理设置：
                WebProxy proxy = new WebProxy();
                Uri proxyURI = new Uri("http://" + proxyString);
                proxy.Address = proxyURI;
                request.Proxy = proxy;

                request.Accept = "*/*";
                request.UserAgent = "Mozilla/4.0 (MSIE 6.0; Windows NT 8982 )";
                request.Headers["Accept-Language"] = "zh-cn";
                request.Timeout = 6000;


                HttpWebResponse oWebResp = (HttpWebResponse)request.GetResponse();
                StreamReader oStream = new StreamReader(oWebResp.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
                string sResp = oStream.ReadToEnd();
                oStream.Close();
            }
            catch
            {
                this.OnMessageSend(this, new ProxyInfoArgs(proxyString, -1));
                //                this.EndThread();
                return;
            }
            watch.Stop();
            this.OnMessageSend(this, new ProxyInfoArgs(proxyString, (int)(1000000F / watch.ElapsedMilliseconds)));
//            this.EndThread();
        }

        public void StartThread()
        {
            testThread = new System.Threading.Thread(new System.Threading.ThreadStart(TestProxy));
            testThread.Start();
        }
        public void EndThread()
        {
            testThread.Abort();
        }

    }

}